<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          :model="loginForm"
          :rules="rules"
          class="login-form"
          ref="loginFormRefs"
        >
          <h1>Hello</h1>
          <h2>欢迎使用后台管理系统</h2>
          <el-form-item prop="userName">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.userName"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              v-model="loginForm.password"
              type="password"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              type="primary"
              class="login-btn"
              @click="login"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import useUserStore from '@/store/modules/user'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
// 引入当前时间函数
import { getTime } from '@/utils/time'
let $router = useRouter()
let $route = useRoute()
let userStore = useUserStore()
// 获取el-form组件
let loginFormRefs = ref()
let loginForm = reactive({
  userName: '',
  password: '',
  sysCode: 'cashCenter',
})
const loading = ref(false)
// 登录按钮回调
const login = async () => {
  await loginFormRefs.value.validate()
  // 开始加载
  loading.value = true
  try {
    await userStore.userLogin(loginForm)
    // 判断登录时，路由路径中是否有query参数，如果有就往query参数页跳转，没有跳转首页
    let redirect: string = $route.query.redirect;
    $router.push(redirect || '')
    ElNotification({
      type: 'success',
      message: '欢迎回来！',
      title: `HI,${getTime()}好`,
    })
  } catch (err) {
    ElNotification({
      type: 'error',
      message: (err as Error).message,
    })
  } finally {
    loading.value = false
  }
}

// 表单校验
const rules = {
  userName: [
    {required: true, message: '用户名不能为空', trigger: ["blur"]}
  ],
  password: [{required: true, message: '密码不能为空', trigger: ["blur"]}],
}
</script>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: 100% 100%;

  .login-form {
    position: relative;
    width: 55%;
    top: 25vh;
    left: 10vw;
    padding: 10px;
    background: transparent;
    h1 {
      color: #333;
      font-size: 40px;
    }
    h2 {
      font-size: 22px;
      margin: 20px 0;
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>
